package com.lixh.sdk.base

import android.app.ActivityManager
import android.content.Context
import android.content.res.Configuration
import android.content.res.Resources
import android.os.Process
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.multidex.MultiDex
import androidx.multidex.MultiDexApplication
import com.tencent.mmkv.MMKV
import net.danlew.android.joda.JodaTimeAndroid
import kotlin.properties.Delegates


/**
 * APPLICATION
 */
abstract class BaseApplication : MultiDexApplication(), LifecycleObserver {

    // 方法名随便取，注解才是重点
    private val myEventObserver = LifecycleEventObserver { _, event ->
        when (event) {
            Lifecycle.Event.ON_CREATE -> toFront()
            Lifecycle.Event.ON_START -> toBack()
            else -> {}
        }
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        MultiDex.install(this);
        JodaTimeAndroid.init(this)
        MMKV.initialize(this)
        ProcessLifecycleOwner.get().lifecycle.addObserver(myEventObserver)
        //防止独立进程多次执行Application中onCreate的初始化方法
        initApp()
        if (shouldInit()) {
            initMainProcess()
        } else {
            initOtherProcess()
        }

    }


    open fun initApp() {

    }

    abstract fun initMainProcess()

    //特殊需要 如 友盟推送 需要 主进程和子进程（:channel）均需要调用推送注册接口，否则退到后台会有收不到消息的问题。
    open fun initOtherProcess() {

    }

    open fun toBack() {

    }

    open fun toFront() {

    }

    private fun shouldInit(): Boolean {
        val am = getSystemService(ACTIVITY_SERVICE) as ActivityManager
        val processInfos = am.runningAppProcesses
        val mainProcessName = packageName
        val myPid = Process.myPid()
        for (info in processInfos) {
            if (info.pid == myPid && mainProcessName == info.processName) {
                return true
            }
        }
        return false
    }


    //设置字体为默认大小，不随系统字体大小改而改变
    override fun onConfigurationChanged(newConfig: Configuration) {
        if (newConfig.fontScale != 1f) //非默认值
            resources
        super.onConfigurationChanged(newConfig)
    }


    override fun getResources(): Resources {
        var resources = super.getResources()
        val newConfig = resources!!.configuration
        val displayMetrics = resources.displayMetrics
        if (newConfig.fontScale != 1f) {
            newConfig.fontScale = 1f
            val configurationContext: Context = createConfigurationContext(newConfig)
            resources = configurationContext.resources
            displayMetrics.scaledDensity = displayMetrics.density * newConfig.fontScale
        }
        return resources
    }

    companion object {

        var instance: BaseApplication by Delegates.notNull()

        val appContext: Context
            get() = instance.applicationContext

    }

}
